from django.shortcuts import render

# Create your views here.

# 视图
from rest_framework import generics
from rest_framework import viewsets
from rest_framework import mixins
# 分页
from rest_framework.pagination import PageNumberPagination
# 数据过滤
from rest_framework import filters
from django_filters.rest_framework import DjangoFilterBackend
# token配置
from rest_framework.authentication import TokenAuthentication

# 自定义的过滤器
from .filters import GoodsFilter
# 导入模型
from .models import Goods, GoodsCategory
# 导入 serializers
from .serializers import GoodsSerializer, CategorySerializer


class GoodsPagination(PageNumberPagination):
    """
    商品自定义的分页
    """
    page_size = 20  # 设置单页的量 前端可以通过提交 page_size 参数来修改，这里只是个默认值
    max_page_size = 100  # 设置单页最大值
    page_size_query_param = 'page_size'  # 自定义每页数量请求参数
    page_query_param = "p"  # 自定义页数请求参数


class GoodsListViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):
    """
    商品列表页
    """
    queryset = Goods.objects.all()  # 有了 get_queryset 则可不用设置
    serializer_class = GoodsSerializer  # 自定义的 Serializer
    pagination_class = GoodsPagination  # 调用自定义的分页

    authentication_classes = (TokenAuthentication, )  # 配置是否需要 token

    # 设置过滤
    # SearchFilter 搜索
    # filters.OrderingFilter 排序
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
    filter_class = GoodsFilter

    # 设置搜索
    search_fields = ('name', 'goods_brief', 'goods_desc')

    # 过滤的区域
    ordering_fields = ('sold_num', 'shop_price')


# mixins.RetrieveModelMixin 用于获取商品详情
# viewsets.GenericViewSet 加了之后，可以直接通过 http://127.0.0.1:8000/category/(id) 的方式获取详情
class CategoryViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet):
    """
    list:商品分类列表数据
    """
    queryset = GoodsCategory.objects.filter(category_type=1)  # 只是拼出 sql 脚本并未执行
    serializer_class = CategorySerializer


class GoodsDetailViewset(mixins.RetrieveModelMixin, viewsets.GenericViewSet):
    """
    商品详情
    """
    queryset = Goods.objects.all()
    serializer_class = GoodsSerializer  # 自定义的 Serializer
    lookup_field = "id"
